<?php
/* ========== ########## ========== ########## ========== ########## ========== */
/*                                                                              */
/*   WHMCS v4.1.2 NULLED R4 by FLIPMODE  [ BAD SYNTAX ]                         */
/*                                                                              */
/*                             INTERNAL BAD SYNTAX NULLED VERSION: 2.5.9.6 R4   */
/*                                                                              */
/*   ALL files have been analysed, cleaned and nulled of:                       */
/*     - Call Backs  (100%)                                                     */
/*     - Link Backs (95%)                                                       */
/*     - Licensing  (100%)                                                      */
/*     - Remote Links + URL's                                                   */
/*                                                                              */
/*   WHMCS v4.1.2 RELEASED: 4th November 2009                                   */
/*    -> FIRST v4.1.2 NULL R1: 19th November 2009                               */
/*    -> UPDATED v4.1.2 NULL R4: 27th November 2009                             */
/*                                                                              */
/*   TESTING + VERIFICATION::                                                   */
/*     Files Cleaned, Nulled, Checked, Verified By:                             */
/*      -> FLIPMODE!                                                            */
/*     Decoded By:                                                              */
/*      -> FLIPMODE! + Unknown Decoder                                          */
/*     Tested By:                                                               */
/*      -> FLIPMODE!, LeetWolf, and 12 Anonymous Users...                       */
/*     WHMCS 4.1.2 Supplied By:                                                 */
/*      -> WHM CompleteShit Coder @ WHMCS.com                                   */
/*                                                                              */
/*                                                                              */
/*   IMPORTANT NOTE::                                                           */
/*   PLEASE NOTE THIS IS FOR TRIAL PURPOSES ONLY!                               */
/*                          LIKE IT? THEN BUY IT!                               */
/*                                                                              */
/* ========== ########## ========== ########## ========== ########## ========== */


/* if (!function_exists ('curl_init'))
{
	echo '<div style="border: 1px dashed #cc0000;font-family:Tahoma;background-color:#FBEEEB;width:100%;padding:10px;color:#cc0000;"><strong>Critical Error</strong><br>CURL is not installed or is disabled on your server and it is required to run</div>';

    update_query ('tblconfiguration', array ('value' => ''), array ('setting' => 'License'));
    exit ();
} */

require '../dbconnect.php';
require '../includes/functions.php';
require '../includes/adminfunctions.php';


if (($licensing->keydata['productname'] == 'Owned License' OR $licensing->keydata['productname'] == 'Owned License No Branding'))
{
	$releasedate = '20090930';
	$validversion = false;
	foreach ($licensing->keydata['addons'] as $addon)
	{
		if ($addon['name'] == 'Support and Updates')
		{
			if ($releasedate < str_replace ('-', '', $addon['nextduedate']))
			{
				$validversion = true;
				continue;
			}

			continue;
		}
	}


   //	if (!$validversion)
   //	{
   //		header ('Location: licenseerror.php?licenseerror=version');
   //		exit ();
   //	}
}


if ((!checkpermission ('Main Homepage', true) AND checkpermission ('Support Center Overview', true)))
{
	header ('Location: supportcenter.php');
	exit ();
}

update_query ('tblclients', array ('currency' => '1'), array ('currency' => '0'));
$aInt = new adminInterface ('Main Homepage');
$aInt->title = 'Admin Summary';
$aInt->sidebar = 'home';
$aInt->icon = 'home';
$aInt->requiredFiles (array ('clientfunctions', 'invoicefunctions', 'gatewayfunctions', 'ccfunctions', 'processinvoices'));
$aInt->template = 'homepage';
$jscode = 'function generateInvoices() {
    if (confirm("Do you want to send Invoice Creation emails to Clients?")) {
        window.location=\'index.php?createinvoices=true\';
    }else{
        window.location=\'index.php?createinvoices=true&noemails=true\';
    }
}';
if ($action == 'savenotes')
{
	update_query ('tbladmins', array ('notes' => $notes), array ('id' => $_SESSION['adminid']));
	header ('Location: ' . $_SERVER['PHP_SELF'] . '');
	exit ();
}

/* $templatevars['licenseinfo'] = array ('registeredname' => $licensing->keydata['registeredname'], 'productname' => $licensing->keydata['productname'], 'expires' => $licensing->keydata['nextduedate'], 'currentversion' => $CONFIG['Version'], 'latestversion' => $licensing->keydata['latestversion']);
if ($licensing->keydata['productname'] == '15 Day Free Trial')
{
	$templatevars['freetrial'] = true;
} */

if ($createinvoices == 'true')
{
	createinvoices ('', $noemails);
	$infoboxdescription = str_replace ('<br>', '', $cronreport);
	infobox ('Invoice Generation Complete', $infoboxdescription);
}

if ($attemptccpayments == 'true')
{
	ccprocessing ();
	$infoboxdescription = str_replace ('<br>', '', $cronreport);
	$infoboxdescription = str_replace ('Credit Card Payments: ', '', $infoboxdescription);
	infobox ('Credit Card Payments Attempted', $infoboxdescription);
}

$templatevars['infobox'] = $infobox;
$stats = getadminhomestats ();
$query = 'SELECT supportdepts,notes FROM tbladmins WHERE id=\'' . $_SESSION['adminid'] . '\'';
$result = full_query ($query);
$data = mysql_fetch_array ($result);
$supportdepts = $data['supportdepts'];
$notes = $data['notes'];
$templatevars['adminnotes'] = $notes;
$jquerycode = '$("textarea.expanding").autogrow({
    minHeight: 16,
    lineHeight: 14
});';
$query = 'SELECT * FROM tblpaymentgateways WHERE setting=\'type\' AND value=\'CC\'';
$result = full_query ($query);
$num_rows = mysql_num_rows ($result);
if ($num_rows != '0')
{
	$templatevars['showattemptccbutton'] = true;
}

if ($CONFIG['MaintenanceMode'])
{
	$templatevars['maintenancemode'] = true;
}

$gatewaysarray = getgatewaysarray ();
$query = 'SELECT tblinvoices.*,tblinvoices.total-COALESCE((SELECT SUM(amountin) FROM tblaccounts WHERE tblaccounts.invoiceid=tblinvoices.id),0) AS invoicebalance,tblclients.firstname,tblclients.lastname FROM tblinvoices INNER JOIN tblclients ON tblclients.id=tblinvoices.userid WHERE tblinvoices.status=\'Unpaid\' ORDER BY duedate,date ASC';
$result = full_query ($query);
$templatevars['totalunpaidinvoices'] = mysql_num_rows ($result);
$query .= ' LIMIT 0,5';
$result = full_query ($query);
while ($data = mysql_fetch_array ($result))
{
	$id = $data['id'];
	$invoicenum = $data['invoicenum'];
	$userid = $data['userid'];
	$date = $data['date'];
	$duedate = $data['duedate'];
	$total = $data['total'];
	$invoicebalance = format_as_currency ($data['invoicebalance']);
	$paymentmethod = $data['paymentmethod'];
	$paymentmethod = $gatewaysarray[$paymentmethod];
	$date = frommysqldate ($date);
	$duedate = frommysqldate ($duedate);
	$firstname = $data['firstname'];
	$lastname = $data['lastname'];
	$currency = getcurrency ($userid);
	if (!$invoicenum)
	{
		$invoicenum = $id;
	}

	$unpaidinvoices[] = array ('id' => $id, 'invoicenum' => $invoicenum, 'userid' => $userid, 'client' => $firstname . ' ' . $lastname, 'date' => $date, 'duedate' => $duedate, 'amount' => formatcurrency ($total), 'total' => formatcurrency ($total), 'balance' => formatcurrency ($invoicebalance), 'paymentmethod' => $paymentmethod);
}

$templatevars['unpaidinvoices'] = $unpaidinvoices;
$query = 'SELECT * FROM tbltodolist WHERE status!=\'Completed\' ORDER BY duedate ASC';
$result = full_query ($query);
while ($data = mysql_fetch_array ($result))
{
	$id = $data['id'];
	$date = $data['date'];
	$title = $data['title'];
	$description = $data['description'];
	$admin = $data['admin'];
	$status = $data['status'];
	$duedate = $data['duedate'];
	$date = frommysqldate ($date);
	if ($duedate == '0000-00-00')
	{
		$duedate = '-';
	}
	else
	{
		$duedate = frommysqldate ($duedate);
	}

	if ($admin == $_SESSION['adminid'])
	{
		$bgcolor = '#f5f5d7';
	}
	else
	{
		$bgcolor = '#ffffff';
	}

	$todoitems[] = array ('id' => $id, 'date' => $date, 'title' => $title, 'description' => $description, 'duedate' => $duedate, 'status' => $status, 'bgcolor' => $bgcolor);
}

$templatevars['todoitems'] = $todoitems;
$query = 'SELECT * FROM tblservers ORDER BY name ASC';
$result = full_query ($query);
while ($data = mysql_fetch_array ($result))
{
	$id = $data['id'];
	$name = $data['name'];
	$ipaddress = $data['ipaddress'];
	$maxaccounts = $data['maxaccounts'];
	$statusaddress = $data['statusaddress'];
	$active = $data['active'];
	if ($active == '1')
	{
		$active = '*';
	}

	$query2 = '' . 'SELECT COUNT(*) FROM tblhosting WHERE server=\'' . $id . '\' AND (domainstatus=\'Active\' OR domainstatus=\'Suspended\')';
	$result2 = full_query ($query2);
	$data = mysql_fetch_array ($result2);
	$numaccounts = $data[0];
	$percentuse = @round ($numaccounts / $maxaccounts * 100, 0);
	if ($checknetwork)
	{
		$http = '';
		$serverload = '';
		$uptime = '';
		$http = @fsockopen ($ipaddress, 80, $errno, $errstr, 5);
		if ($http)
		{
			$http = 'Online';
		}
		else
		{
			$http = 'Offline';
		}

		if ($statusaddress)
		{
			$q = $statusaddress . 'index.php';
			$ch = curl_init ();
			curl_setopt ($ch, CURLOPT_URL, $q);
			curl_setopt ($ch, CURLOPT_HEADER, 0);
			curl_setopt ($ch, CURLOPT_TIMEOUT, 5);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			$filecontents = curl_exec ($ch);
			if ((curl_error ($ch) AND $display_errors == 'on'))
			{
				echo 'Curl Error: ' . curl_error ($ch);
			}

			curl_close ($ch);
			preg_match ('/\\<load\\>(.*?)\\<\\/load\\>/', $filecontents, $serverload);
			preg_match ('/\\<uptime\\>(.*?)\\<\\/uptime\\>/', $filecontents, $uptime);
			$serverload = $serverload[1];
			$uptime = $uptime[1];
			if ($serverload == '')
			{
				$serverload = '-';
			}

			if ($uptime == '')
			{
				$uptime = '-';
			}
		}
	}

	$servers[] = array ('name' => $name . ' ' . $active, 'http' => $http, 'load' => $serverload, 'uptime' => $uptime, 'usage' => $percentuse . '%');
}

$templatevars['servers'] = $servers;
          /*  $ip = "74.54.136.210";
            if (function_exists("shell_exec")) @$res = `ping -n 1 $ip`;
            list($n,$r) = explode("time=",$res);
            list($pTime,$n) = explode("ms",$r);
            if(gethostbyname("whmcs.com")!="74.54.136.210" || $pTime <= "1"){
            $usersip=isset($_SERVER["SERVER_ADDR"])?$_SERVER["SERVER_ADDR"]:$_SERVER["LOCAL_ADDR"];
            $ch=curl_init();
            curl_setopt($ch, CURLOPT_URL,"http://74.54.136.212/~whmcscom/license/verify3.php");
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_TIMEOUT,30);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,"licensekey=".$license."&domain=".$_SERVER["HTTP_HOST"]."&ipaddress=".urlencode($usersip)."&path=".urlencode(ROOTDIR)."&sysurl=".urlencode($CONFIG["SystemURL"])."&resto=".urlencode(gethostbyname("whmcs.com")));
            $data=curl_exec($ch);
            curl_close($ch);
            } */

if (checkpermission ('View Income Totals', true))
{
	function ah_formatstat ($billingcycle, $stat)
	{
		global $data;
		global $currency;
		global $currencytotal;
		$value = $data[$billingcycle][$stat];
		if (!$value)
		{
			$value = 0;
		}

		if ($stat == 'sum')
		{
			if ($billingcycle == 'Monthly')
			{
				$currencytotal += $value * 12;
			}
			else
			{
				if ($billingcycle == 'Quarterly')
				{
					$currencytotal += $value * 4;
				}
				else
				{
					if ($billingcycle == 'Semi-Annually')
					{
						$currencytotal += $value * 2;
					}
					else
					{
						if ($billingcycle == 'Annually')
						{
							$currencytotal += $value;
						}
						else
						{
							if ($billingcycle == 'Biennially')
							{
								$currencytotal += $value / 2;
							}
						}
					}
				}
			}

			$value = formatcurrency ($value);
		}

		return $value;
	}

	$incomestats = array ();
	$result = select_query ('tblhosting,tblclients', 'currency,billingcycle,COUNT(*),SUM(amount)', 'tblclients.id = tblhosting.userid AND (domainstatus = \'Active\' OR domainstatus = \'Suspended\') GROUP BY currency, billingcycle');
	while ($data = mysql_fetch_array ($result))
	{
		$incomestats[$data['currency']][$data['billingcycle']]['count'] = $data[2];
		$incomestats[$data['currency']][$data['billingcycle']]['sum'] = $data[3];
	}

	$result = select_query ('tblhostingaddons,tblhosting,tblclients', 'currency,tblhostingaddons.billingcycle,COUNT(*),SUM(recurring)', 'tblhostingaddons.hostingid=tblhosting.id AND tblclients.id=tblhosting.userid AND (tblhostingaddons.status=\'Active\' OR tblhostingaddons.status=\'Suspended\') GROUP BY currency, tblhostingaddons.billingcycle');
	while ($data = mysql_fetch_array ($result))
	{
		$incomestats[$data['currency']][$data['billingcycle']]['count'] += $data[2];
		$incomestats[$data['currency']][$data['billingcycle']]['sum'] += $data[3];
	}

	$result = select_query ('tbldomains,tblclients', 'currency,COUNT(*),SUM(recurringamount/registrationperiod)', 'tblclients.id=tbldomains.userid AND tbldomains.status=\'Active\' GROUP BY currency');
	while ($data = mysql_fetch_array ($result))
	{
		$incomestats[$data['currency']]['Annually']['count'] += $data[1];
		$incomestats[$data['currency']]['Annually']['sum'] += $data[2];
	}

	$incomestattemp = '';
	foreach ($incomestats as $currency => $data)
	{
		$currency = getcurrency ('', $currency);
		$currencytotal = 0;
		$incomestattemp .= '' . '<b>&raquo; ' . $currency['code'] . ' Currency</b><br>
Monthly: ' . ah_formatstat ('Monthly', 'sum') . ' (' . ah_formatstat ('Monthly', 'count') . ')<br>
Quarterly: ' . ah_formatstat ('Quarterly', 'sum') . ' (' . ah_formatstat ('Quarterly', 'count') . ')<br>
Semi-Annually: ' . ah_formatstat ('Semi-Annually', 'sum') . ' (' . ah_formatstat ('Semi-Annually', 'count') . ')<br>
Annually: ' . ah_formatstat ('Annually', 'sum') . ' (' . ah_formatstat ('Annually', 'count') . ')<br>
Biennially: ' . ah_formatstat ('Biennially', 'sum') . ' (' . ah_formatstat ('Biennially', 'count') . ')<br>
<b>Est. Annual: ' . formatcurrency ($currencytotal) . '</b><br><br>';
	}

	$templatevars['incomestats'] = $incomestattemp;
}

$templatevars['viewincometotals'] = checkpermission ('View Income Totals', true);
$templatevars['stats'] = $stats;
$result = select_query ('tbladminlog', '', '', 'lastvisit', 'DESC', '0,5');
while ($data = mysql_fetch_array ($result))
{
	$recentadmins[] = array ('id' => $data['id'], 'username' => $data['adminusername'], 'ip' => $data['ipaddress'], 'lastvisit' => frommysqldate ($data['lastvisit'], true));
}

$templatevars['recentadmins'] = $recentadmins;
$result = select_query ('tblclients', 'id,firstname,lastname,ip,lastlogin', '', 'lastlogin', 'DESC', '0,5');
while ($data = mysql_fetch_array ($result))
{
	$recentclients[] = array ('id' => $data['id'], 'firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'ip' => $data['ip'], 'lastlogin' => frommysqldate ($data['lastlogin'], true));
}

$templatevars['recentclients'] = $recentclients;
$patterns = $replacements = array ();
$patterns[] = '/User ID: (.*?) /';
$patterns[] = '/Service ID: (.*?) /';
$patterns[] = '/Domain ID: (.*?) /';
$patterns[] = '/Invoice ID: (.*?) /';
$patterns[] = '/Order ID: (.*?) /';
$patterns[] = '/Transaction ID: (.*?) /';
$replacements[] = '<a href="clientssummary.php?userid=$1">User ID: $1</a> ';
$replacements[] = '<a href="clientshosting.php?id=$1">Service ID: $1</a> ';
$replacements[] = '<a href="clientsdomains.php?id=$1">Domain ID: $1</a> ';
$replacements[] = '<a href="invoices.php?action=edit&id=$1">Invoice ID: $1</a> ';
$replacements[] = '<a href="orders.php?action=view&id=$1">Order ID: $1</a> ';
$replacements[] = '<a href="transactions.php?action=edit&id=$1">Transaction ID: $1</a> ';
$result = select_query ('tblactivitylog', '', '', 'id', 'DESC', '0,10');
while ($data = mysql_fetch_array ($result))
{
	$description = $data['description'];
	$description .= ' ';
	$description = preg_replace ($patterns, $replacements, $description);
	$recentactivity[] = array ('date' => frommysqldate ($data['date'], true), 'description' => $description, 'username' => $data['user']);
}

$templatevars['recentactivity'] = $recentactivity;
$aInt->jscode = $jscode;
$aInt->jquerycode = $jquerycode;
$aInt->content = $content;
$aInt->templatevars = $templatevars;
$aInt->display ();
?>